import sys
import os
import json
import sqlite3

def query_db_for_file(db_folder, db_filename, table_name, file_hash):
    """Query the database for a specific file hash and return its details."""
    try:
        # Connect to the SQLite database with UTF-8 encoding support
        conn = sqlite3.connect(os.path.join(db_folder, db_filename))
        conn.text_factory = str  # Ensure strings are treated as UTF-8
        cursor = conn.cursor()

        # Query the database for the given file hash
        query = f"SELECT zip_path, zip_name, file_path, file_name FROM {table_name} WHERE file_hash = ?"
        cursor.execute(query, (file_hash,))
        result = cursor.fetchone()

        if result is None:
            return json.dumps({"error": f"No matching entry found for hash {file_hash}"}, ensure_ascii=False)

        # Extract the results
        zip_path, zip_name, file_path, file_name = result

        # Prepare the result dictionary
        result_dict = {
            "zip_path": zip_path,
            "zip_name": zip_name,
            "file_path": file_path,
            "file_name": file_name
        }

        # Return JSON output with ensure_ascii=False to preserve non-ASCII characters
        return json.dumps(result_dict, ensure_ascii=False)

    except sqlite3.Error as e:
        return json.dumps({"error": f"Database error: {e}"}, ensure_ascii=False)
    finally:
        if conn:
            conn.close()

if __name__ == '__main__':
    # Ensure the correct number of arguments are provided
    if len(sys.argv) != 5:
        print(json.dumps({"error": "Four arguments required: DB folder, DB filename, table name, and file hash"}, ensure_ascii=False))
    else:
        db_folder = sys.argv[1]
        db_filename = sys.argv[2]
        table_name = sys.argv[3]
        file_hash = sys.argv[4]

        # Print inputs for debugging purposes
        print(f"Received DB folder: {db_folder}")
        print(f"Received DB filename: {db_filename}")
        print(f"Received table name: {table_name}")
        print(f"Received file hash: {file_hash}")

        print(query_db_for_file(db_folder, db_filename, table_name, file_hash))
        
# e.g. python .\m12_query_fileinzip.py "D:\photo\base" "file_hashes.db" "photo_hash" 3b70a095440276b7670009b60ea55a77f1fd4442cb321d4bb749ce431bd62fb9